<script lang="ts" setup>
import type { Recordable } from '@vben/types';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { UserItem } from '#/api/system/user';

import { Page, useVbenDrawer } from '@vben/common-ui';
import { Plus, Upload, Download } from '@vben/icons';
import { ElButton, ElMessage, ElMessageBox } from 'element-plus';
import { h, ref, onMounted, nextTick, computed } from 'vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  getUserList,
  getUserDetail,
  deleteUser,
  batchDeleteUsers,
  updateUserStatus
} from '#/api/system/user';
import { $t } from '#/locales';

import { useColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
import AssignRoles from './modules/assign-roles.vue';

// 开发环境标志
const isDev = ref(import.meta.env.DEV);

// 初始化表单抽屉
const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: Form,
  destroyOnClose: true,
});

// 角色分配组件实例
const assignRolesRef = ref<InstanceType<typeof AssignRoles> | null>(null);



// 表格实例
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    fieldMappingTime: [['createdTime', ['startTime', 'endTime']]],
    schema: useGridFormSchema(),
    submitOnChange: true,
  },
  gridOptions: {
    columns: useColumns(onActionClick),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getUserList({
            pageIndex: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
      props: {
        result: 'items',
        total: 'totalCount'
      }
    },
    rowConfig: {
      keyField: 'id',
    },
    toolbarConfig: {
      custom: true,
      export: false,
      refresh: { code: 'query' },
      search: true,
      zoom: true,
    },
  } as VxeTableGridOptions<UserItem>,
});

// 操作按钮点击事件
function onActionClick(params: { code: string; row: UserItem }) {
  switch (params.code) {
    case 'delete': {
      onDelete(params.row);
      break;
    }
    case 'edit': {
      onEdit(params.row);
      break;
    }
    case 'resetPassword': {
      onResetPassword(params.row);
      break;
    }
    case 'detail': {
      onViewDetail(params.row);
      break;
    }
    case 'assignRoles': {
      onAssignRoles(params.row);
      break;
    }
    case 'changeStatus': {
      onChangeStatus(params.row);
      break;
    }
  }
}

// 修改用户状态
function onChangeStatus(row: UserItem) {
  // 系统用户不允许修改
  if (row.userType === 2) {
    ElMessage.warning($t('system.user.systemUserHint'));
    return;
  }

  // 获取当前状态的下一个状态（循环：0->1->2->3->0）
  const nextStatus = (row.status + 1) % 4;

  // 状态映射
  const statusMap: Record<number, string> = {
    0: $t('system.user.status_type.normal'),
    1: $t('system.user.status_type.disabled'),
    2: $t('system.user.status_type.locked'),
    3: $t('system.user.status_type.inactive')
  };

  // 显示确认对话框
  ElMessageBox.confirm(
    `确定要将${row.userName}的状态从【${statusMap[row.status]}】修改为【${statusMap[nextStatus]}】吗？`,
    $t('system.user.changeStatus'),
    {
      confirmButtonText: $t('common.confirm'),
      cancelButtonText: $t('common.cancel'),
      type: 'warning'
    }
  ).then(async () => {
    try {
      await updateUserStatus({ userId: row.id, status: nextStatus });
      ElMessage.success($t('system.user.updateStatusSuccess'));
      onRefresh(); // 刷新列表
    } catch (error) {
      ElMessage.error($t('common.operationFailed'));
    }
  }).catch(() => {
    // 用户取消，不做任何操作
  });
}

// 编辑用户
function onEdit(row: UserItem) {
  try {
    // 移除对象中可能存在的undefined值
    const userData = { ...row } as Record<string, any>;
    Object.keys(userData).forEach(key => {
      if (userData[key] === undefined) {
        userData[key] = null;
      }
    });

    // 使用抽屉API设置数据并打开抽屉
    formDrawerApi.setData(userData).open();
  } catch (error) {
    console.error("编辑用户时出错:", error);
    ElMessage.error($t('common.operationFailed'));
  }
}

// 重置密码
function onResetPassword(row: UserItem) {
  ElMessage.warning('功能开发中');
}

// 查看用户详情
function onViewDetail(row: UserItem) {
  ElMessage.warning('功能开发中');
}

// 分配角色
async function onAssignRoles(row: UserItem) {
  try {
    // 获取用户详情，确保获取到roleIds
    const userDetail = await getUserDetail(row.id);

    // 使用组件实例方法打开抽屉
    if (assignRolesRef.value) {
      assignRolesRef.value.setData({
        id: row.id,
        userName: row.userName,
        roleIds: userDetail.roleIds || []
      });
    }
  } catch (error) {
    console.error("分配角色时出错:", error);
    ElMessage.error($t('common.operationFailed'));
  }
}

// 打开导入界面
function onImport() {
  ElMessage.warning('功能开发中');
}

// 打开导出界面
function onExport() {
  ElMessage.warning('功能开发中');
}

// 删除用户
function onDelete(row: UserItem) {
  // 系统用户不允许删除
  if (row.userType === 2) {
    ElMessage.warning($t('system.user.systemUserHint'));
    return;
  }

  ElMessageBox.confirm($t('system.user.deleteConfirm'), $t('common.warning'), {
    confirmButtonText: $t('common.confirm'),
    cancelButtonText: $t('common.cancel'),
    type: 'warning',
  }).then(async () => {
    ElMessage({
      message: $t('actionMessage.deleting', [row.userName]),
      type: 'info',
    });

    try {
      await deleteUser(row.id);
      ElMessage.success($t('system.user.deleteSuccess'));
      onRefresh();
    } catch (error) {
      ElMessage.error($t('actionMessage.deleteFailed', [row.userName]));
    }
  }).catch(() => {});
}

// 批量删除
async function onBatchDelete() {
  const selectedRows = gridApi?.grid?.getCheckboxRecords() || [];
  if (!selectedRows.length) {
    ElMessage.warning($t('common.table.noRowSelected'));
    return;
  }

  // 检查是否包含系统用户
  const systemUsers = selectedRows.filter((row: UserItem) => row.userType === 2);
  if (systemUsers.length > 0) {
    ElMessage.warning($t('system.user.systemUserHint'));
    return;
  }

  ElMessageBox.confirm($t('system.user.batchDeleteConfirm'), $t('common.warning'), {
    confirmButtonText: $t('common.confirm'),
    cancelButtonText: $t('common.cancel'),
    type: 'warning',
  }).then(async () => {
    const userIds = selectedRows.map((row: UserItem) => row.id);
    try {
      const count = await batchDeleteUsers(userIds);
      ElMessage.success($t('system.user.batchDeleteSuccess', { count }));
      onRefresh();
    } catch (error) {
      ElMessage.error($t('common.actionMessage.failed'));
    }
  }).catch(() => {});
}

// 刷新表格
function onRefresh() {
  gridApi.query();
}

// 创建用户
function onCreate() {
  try {
    // 初始化数据对象
    const initData = {
      userName: '',
      realName: '',
      nickName: '',
      email: '',
      phoneNumber: '',
      gender: 0,
      userType: 0,
      status: 0,
      biography: '',
      birthDate: null
    };

    // 使用抽屉API设置数据并打开抽屉
    formDrawerApi.setData(initData).open();
  } catch (error) {
    console.error("创建用户时出错:", error);
    ElMessage.error($t('common.operationFailed'));
  }
}

// 表单提交成功后刷新表格
function onFormSuccess() {
  onRefresh();
}

// 角色分配成功后刷新表格
function onAssignRolesSuccess() {
  onRefresh();
}
</script>

<template>
  <Page auto-content-height>
    <!-- 用户表单抽屉 -->
    <FormDrawer @success="onFormSuccess" />

    <!-- 角色分配抽屉 -->
    <AssignRoles ref="assignRolesRef" @success="onAssignRolesSuccess" />

    <Grid :table-title="$t('system.user.list')">
      <template #toolbar-tools>
        <el-button type="primary" @click="onCreate">
          <Plus class="size-5" />
          {{ $t('common.create') }}
        </el-button>
        <el-button type="danger" @click="onBatchDelete">
          {{ $t('common.batchDelete') }}
        </el-button>
        <el-button @click="onImport">
          <Upload class="size-5" />
          {{ $t('system.user.import') }}
        </el-button>
        <el-button @click="onExport">
          <Download class="size-5" />
          {{ $t('system.user.export') }}
        </el-button>
      </template>
    </Grid>

  </Page>
</template>
